package com.cuit.interceptors;

import com.alibaba.fastjson.JSON;
import com.cuit.pojo.Users;
import com.cuit.utils.RedisUtils;
import com.cuit.utils.Result;
import com.cuit.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptors implements HandlerInterceptor {

    @Autowired
    public RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在执行controller方法之前执行
        /**
         * 需要判断请求的路径，是否为handlerMethod(controller方法）
         * 判断是否token是否为空，如果为空，未登录
         * 如果token不为空，登录验证
         */
        if ( !(handler instanceof HandlerMethod)){
            // handler 可能是RequestResourceHandler springboot程序 访问静态资源，默认去classpath下的static目录去查询
            return true;
        }


        String token = request.getHeader("Authorization");
        System.out.println(token);
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(Result.fail(999,"未登录")));
            return false;
        }
        Object o = redisUtils.get(token);
        log.info("从redis获取----------->{}",o);
        if (o == null){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(Result.fail(999,"未登录")));
            return false;
        }
        redisUtils.expire(token,1500L); // 设置token延迟十分钟
        Users users = JSON.parseObject(o.toString(), Users.class);
        UserThreadLocal.put(users);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove(); // 防止内存泄漏
    }
}
